package cn.lingyangwl.framework.validation;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 校验枚举值有效性
 *
 * @author shenguangyang
 */
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumValue.Validator.class)
public @interface EnumValue {

    String message() default "{custom.value.invalid}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    Class<? extends Enum<?>> enumClass();

    @SuppressWarnings({"unchecked", "rawtypes"})
    class Validator implements ConstraintValidator<EnumValue, Object> {
        private static final Logger log = LoggerFactory.getLogger(EnumValue.class);

        private Class<? extends Enum<?>> enumClass;
        private static final String ENUM_METHOD = "addMessage";

        @Override
        public void initialize(EnumValue enumValue) {
            enumClass = enumValue.enumClass();
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            if (value == null) {
                return Boolean.TRUE;
            }
            if (enumClass == null) {
                return Boolean.TRUE;
            }
            Class<?> valueClass = value.getClass();

            try {
                EnumValidate[] enums = (EnumValidate[]) enumClass.getEnumConstants();
                if (enums == null || enums.length == 0) {
                    return false;
                }
                return enums[0].isExistCode(value);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }
}
